import {
  notification,
} from 'antd';

// dispatch（type，payload，callback）

/**
 * call 数据获取
 * put 状态更新
 * set 状态更新
 * select 状态获取
 * lead 状态转移，附带状态检查
 * may 状态检查/ '可以继续'
 */
export const useOperation = ({call, put, select}) => ({
  call,
  put,
  * set (newState) {
    for (const key in newState) {
      if (newState.hasOwnProperty(key)) {
        yield put({
          type: key,
          payload: newState[key],
        })
      }
    }
  },
  select,
  may (res) {
    if (res && res.code !== 0) {
      notification.error({
        message: `请求错误 ${res.code}`,
        description: res.msg,
      });

      return false;
    } 
    return true;
  },
  * lead (res, type/** nextAction */, payload /** nextAction's params */) {
    if (typeof res === 'string') {
      type = res;
      payload = type;

      yield put({
        type,
        payload,
      });
    } else {
      if (res && res.code !== 0) {
        notification.error({
          message: `请求错误 ${res.code}`,
          description: res.msg,
        });
      } else {
        if (type) {
          yield put({
            type,
            payload,
          });
        }
      }
    }
  },
  ext (res) {
    const path = res.result && res.result.path;
    if (path) {
      const link = document.createElement('a');
      link.setAttribute('download', '');
      link.href = path;
      link.click();
    } else {
      notification.error({
        message: '该日期范围内无数据导出',
        // description: response.msg,
      });
    }
  },
  imt () {

  }
})